package com.xsq.audio.player;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.jakewharton.rxbinding4.view.RxView;
import com.xsq.audio.AudioItemData;
import com.xsq.audio.IAudioControllerListener;
import com.xsq.audio.R;
import com.xsq.audio.databinding.ActivityPlayerBinding;
import com.xsq.audio.player.adapter.PlayerPagerAdapter;
import com.xsq.audio.player.bean.AudioPositionBean;
import com.xsq.audio.player.fragment.CoverFragment;
import com.xsq.audio.player.playlist.AudioListDialog;
import com.xsq.audio.player.utils.CoverLoader;
import com.xsq.audio.player.utils.FormatUtil;
import com.xsq.audio.player.utils.ImageUtils;
import com.xsq.audio.player.utils.ThreadPoolUtils;
import com.xsq.audio.player.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Consumer;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;


/**
 * Created by Shiquan.Xiao on 2023/3/31.
 */
public class PlayerActivity extends AppCompatActivity {

    private ActivityPlayerBinding binding;
    private final CoverFragment coverFragment = new CoverFragment();
    private final List<Fragment> fragments = new ArrayList<>();
    private final CompositeDisposable cd = new CompositeDisposable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPlayerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        boolean isPlaying = PlayManager.isPlaying();
        if (isPlaying) {
            binding.playPauseIv.play();
        } else {
            binding.playPauseIv.pause();
        }
        UIUtils.updatePlayMode(binding.playModeIv, false);

        //返回
        binding.backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //进度
        binding.progressSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                PlayManager.seekTo(seekBar.getProgress());
            }
        });

        //监听音频进度
        PlayManager.onPlayingPosBus()
                .doOnNext(new Consumer<AudioPositionBean>() {
                    @Override
                    public void accept(AudioPositionBean bean) throws Throwable {
                        setPlayingDuration(bean.getCurPosition(), bean.getDuration());
                    }
                })
                .doOnSubscribe(cd::add)
                .subscribe();

        //播放按钮事件监听
        RxView.clicks(binding.playPauseIv)
                .throttleFirst(200, TimeUnit.MILLISECONDS)
                .doOnNext(new Consumer<Unit>() {
                    @Override
                    public void accept(Unit unit) throws Throwable {
                        playAudio();
                    }
                })
                .doOnSubscribe(cd::add)
                .subscribe();

        //下一首
        RxView.clicks(binding.nextPlayIv)
                .throttleFirst(200, TimeUnit.MILLISECONDS)
                .doOnNext(new Consumer<Unit>() {
                    @Override
                    public void accept(Unit unit) throws Throwable {
                        PlayManager.nextPlay();
                    }
                })
                .doOnSubscribe(cd::add)
                .subscribe();

        //上一首
        RxView.clicks(binding.prevPlayIv)
                .throttleFirst(200, TimeUnit.MILLISECONDS)
                .doOnNext(new Consumer<Unit>() {
                    @Override
                    public void accept(Unit unit) throws Throwable {
                        PlayManager.previous();
                    }
                })
                .doOnSubscribe(cd::add)
                .subscribe();

        //切换播放模式
        RxView.clicks(binding.playModeIv)
                .throttleFirst(200, TimeUnit.MILLISECONDS)
                .doOnNext(new Consumer<Unit>() {
                    @Override
                    public void accept(Unit unit) throws Throwable {
                        UIUtils.updatePlayMode(binding.playModeIv, true);
                    }
                })
                .doOnSubscribe(cd::add)
                .subscribe();

        //打开播放队列
        RxView.clicks(binding.playQueueIv)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .doOnNext(new Consumer<Unit>() {
                    @Override
                    public void accept(Unit unit) throws Throwable {
                        AudioListDialog.Companion.newInstance()
                                .showIt(PlayerActivity.this);
                    }
                })
                .doOnSubscribe(cd::add)
                .subscribe();

        PlayManager.addIAudioControllerListener(controllerListener);

        MediaMetadataCompat curPlayingData = PlayManager.getCurPlayingData();
        if (curPlayingData != null) {
            setTitleText(curPlayingData);
        }

        initViewPager();
    }

    /**
     * 播放和暂停操作
     */
    private void playAudio() {
        boolean isPlaying = binding.playPauseIv.isPlaying();
        if (isPlaying) {
            PlayManager.pause();
        } else {
            PlayManager.play();
        }
    }

    private void initViewPager() {
        fragments.clear();
        fragments.add(coverFragment);
        PlayerPagerAdapter adapter = new PlayerPagerAdapter(this, fragments);
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setPageTransformer(new DepthPageTransformer());

        getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {
            @Override
            public void onFragmentViewCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @NonNull View v, @Nullable Bundle savedInstanceState) {
                if (f == coverFragment) {
                    loadBigImage();
                    coverFragment.startRotateAnimation(PlayManager.isPlaying());
                }
            }
        }, false);
    }

    private void setTitleText(MediaMetadataCompat metadataCompat) {
        String name = metadataCompat.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
        binding.titleIv.setText(name);
    }

    private void loadBigImage() {
        CoverLoader.INSTANCE.loadBigImageView(PlayerActivity.this, null, new Function1<Bitmap, Unit>() {
            @Override
            public Unit invoke(Bitmap bitmap) {
                ThreadPoolUtils utils = ThreadPoolUtils.get();
                utils.execute(new Runnable() {
                    @Override
                    public void run() {
                        Drawable image = ImageUtils.createBlurredImageFromBitmap(PlayerActivity.this, bitmap, 10);
                        utils.runOnMainThread(new Runnable() {
                            @Override
                            public void run() {
                                binding.playingBgIv.setImageDrawable(image);
                                coverFragment.setImageBitmap(bitmap);
                            }
                        });
                    }
                });
                return null;
            }
        });
    }

    private void setPlayingDuration(long pos, long duration) {
        String posStr = "";
        if (pos < 0) {
            posStr = PlayerActivity.this.getString(R.string.play_time);
        } else {
            posStr = FormatUtil.formatTime(pos);
        }
        binding.progressTv.setText(posStr);

        String durationStr = "";
        if (duration < 0) {
            durationStr = PlayerActivity.this.getString(R.string.play_time);
        } else {
            durationStr = FormatUtil.formatTime(duration);
            binding.progressSb.setProgress((int) pos);
            binding.progressSb.setMax((int) duration);
        }
        binding.durationTv.setText(durationStr);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cd.clear();
        PlayManager.removeIAudioControllerListener(controllerListener);
    }

    private final IAudioControllerListener controllerListener = new IAudioControllerListener() {
        @Override
        public void onPlayingData(MediaMetadataCompat data) {
            setTitleText(data);
        }

        @Override
        public void onPlayingState(PlaybackStateCompat state) {
            //正在加载
            binding.playPauseIv.setLoading(state.getState() == PlaybackStateCompat.STATE_BUFFERING);

            if (state.getState() == PlaybackStateCompat.STATE_PLAYING) {
                if (!binding.playPauseIv.isPlaying()) {
                    binding.playPauseIv.play();
                }
                coverFragment.resumeRotateAnimation();
            } else {
                if (state.getState() == PlaybackStateCompat.STATE_PAUSED || state.getState() == PlaybackStateCompat.STATE_BUFFERING) {
                    if (binding.playPauseIv.isPlaying()) {
                        binding.playPauseIv.pause();
                    }
                    coverFragment.stopRotateAnimation();
                }
            }
        }

        @Override
        public void onPlayChange(MediaMetadataCompat metadata, List<AudioItemData> audioItemList) {
            View view = coverFragment.getView();
            if (view != null) {
                setPlayingDuration(-1, -1);
                loadBigImage();

                boolean isPlaying = PlayManager.isPlaying();
                coverFragment.startRotateAnimation(isPlaying);
                if (!isPlaying) {
                    PlayManager.play();
                }
            }
        }

        @Override
        public void onRepeatModeChanged(int repeatMode) {
            UIUtils.updatePlayModeIcon(binding.playModeIv);
        }

        @Override
        public void onShuffleModeChanged(int shuffleMode) {
            UIUtils.updatePlayModeIcon(binding.playModeIv);
        }
    };
}
